#!/bin/bash

CA_HOME=CA

gen_cert()
{
	cd $CA_HOME
	
	ext="
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
"

	if [ -n "$ServerIP" ];  then
		ext="${ext}IP.1 = $ServerIP\n"
	fi
	
	if [ -n "$ServerName" ];  then
		ext="${ext}DNS.1 = $ServerName\n"
	fi
	
	if [ -n "$ServerIP" -o  -n "$ServerName" ]; then
		echo "$ext" > ipdomain.ext
		ext_arg="-extfile ipdomain.ext"
	fi
	
	if [ -n "$Subj" ]; then
		subj_arg="-subj $Subj"
	fi
	
	#name=`cat serial`

	# 生成申请者私钥
	#openssl genrsa -out $name.key 2048

	# 生成申请者签发请求
	openssl req -new -nodes -newkey rsa:2048 -keyout $name.key -out $name.csr  $subj_arg

	# CA签发证书
	openssl ca -batch -in $name.csr -out $name.crt -config conf/ca.conf $ext_arg
	#openssl x509 -req -sha256 -days 3650 -in $name.csr -out $name.crt -CA cacert.pem -CAkey private/cakey.pem -CAcreateserial -extfile ipdomain.ext

	# 查看证书信息
	# openssl x509 -noout -text -in $name.crt
	
	rm $name.csr
	mv $name.crt $name.key certs/
	
	echo "get $name.crt $name.key from certs/"
}


help()
{
	echo "Usage: $0 [options] name"
	echo "options:"
	echo "     -a  server ip address"
	echo "     -n  server domain name"
	echo "     -s  subject"
	echo "     -h  help"
	echo ""	
	echo "eg."
	echo " $0 -n *.xxx.com -s '/O=xxx/CN=*.xxx.com' xxx" 
}


ServerIP=
ServerName=
Subj=

while getopts "a:n:s:" opt; do
  case $opt in
    a)
      ServerIP=$OPTARG
      ;;
    n)
      ServerName=$OPTARG
      ;;
    s)
      Subj=$OPTARG
      ;;    
    h|\?)
      echo "Invalid option: -$OPTARG"
      help
      exit 0
      ;;
  esac
done

shift $(($OPTIND - 1))
name=$1

if [ -z $name ]; then
	echo "Miss name argument"
	help
	exit 0
fi

gen_cert


